package org.jeecg.modules.report.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collector;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.util.SsoUtil;
import org.jeecg.common.util.dahuaVideo.HttpSend;
import org.jeecg.modules.report.entity.ReportConfigVideo;
import org.jeecg.modules.report.service.IReportConfigVideoService;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.report.entity.ReportConfigInfo;
import org.jeecg.modules.report.entity.ReportConfig;
import org.jeecg.modules.report.vo.ReportConfigPage;
import org.jeecg.modules.report.service.IReportConfigService;
import org.jeecg.modules.report.service.IReportConfigInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;

 /**
 * @Description: 战图显示配置
 * @Author: jeecg-boot
 * @Date:   2019-08-20
 * @Version: V1.0
 */
@RestController
@RequestMapping("/b/reportConfig")
@Slf4j
public class ReportConfigController {
	@Autowired
	private IReportConfigService reportConfigService;
	@Autowired
	private IReportConfigInfoService reportConfigInfoService;
	@Autowired
	private IReportConfigVideoService reportConfigVideoService;
    @Autowired
	private ISysUserRoleService sysUserRoleService;

	/**
	  * 分页列表查询
	 * @param reportConfig
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/list")
	public Result<IPage<ReportConfig>> queryPageList(ReportConfig reportConfig,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="5") Integer pageSize,
									  HttpServletRequest req) {
		Result<IPage<ReportConfig>> result = new Result<IPage<ReportConfig>>();
        reportConfig.setProjectName("");
        if (CommonConstant.DEPART_PROPERTY_PROJECT.equals(reportConfig.getDepartType())){
            reportConfig.setSqlMap(sysUserRoleService.dataScopeProjectOnlyFilter(SsoUtil.getLoginUser(),"p",reportConfig.getMenuPath(),null,reportConfig.getDepartIdEx()));
        } else {
            reportConfig.setSqlMap(sysUserRoleService.dataScopeDepartOnlyFilter(SsoUtil.getLoginUser(),"d",reportConfig.getMenuPath(),null,reportConfig.getDepartIdEx()));
        }
		Page<ReportConfig> page = new Page<ReportConfig>(pageNo, pageSize);
        page.setRecords(reportConfigService.findConfigPage(page,reportConfig));
		result.setSuccess(true);
		result.setResult(page);
		return result;
	}
	
	/**
	  *   添加
	 * @param reportConfigPage
	 * @return
	 */
	@PostMapping(value = "/add")
	public Result<ReportConfig> add(@RequestBody ReportConfigPage reportConfigPage) {
		Result<ReportConfig> result = new Result<ReportConfig>();
		try {
			ReportConfig reportConfig = new ReportConfig();
            BeanUtils.copyProperties(reportConfigPage, reportConfig);
            if (StringUtils.isNotBlank(reportConfig.getProjectId())){
                List<ReportConfig> existConfigList =  reportConfigService.findConfigByProjectId(reportConfig.getReportType(),reportConfig.getProjectId());
                if(existConfigList.size() > 0){
                    return Result.error("相同战图类型同一小区不可重复配置");
                }
                reportConfig.setRemarks(reportConfig.getProjectName());

            }else if (StringUtils.isNotBlank(reportConfig.getDepartId())){
                List<ReportConfig> existConfigList = reportConfigService.findConfigByDepartIdOnly(reportConfig.getDepartType(),reportConfig.getDepartId());
                if(existConfigList.size() > 0){
                    return Result.error("相同战图类型同一机构不可重复配置");
                }
                reportConfig.setRemarks(reportConfig.getDepartName());
            }
			reportConfigService.save(reportConfig);
			result.success("添加成功！");
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
		}
		return result;
	}
	
	/**
	  *  编辑
	 * @param reportConfigPage
	 * @return
	 */
	@PutMapping(value = "/edit")
	public Result<ReportConfig> edit(@RequestBody ReportConfigPage reportConfigPage) {
		Result<ReportConfig> result = new Result<ReportConfig>();
		ReportConfig reportConfig = new ReportConfig();
		BeanUtils.copyProperties(reportConfigPage, reportConfig);
		ReportConfig reportConfigEntity = reportConfigService.getById(reportConfig.getId());
		if(reportConfigEntity==null) {
			result.error500("未找到对应实体");
		}else {
			reportConfigService.updateById(reportConfig);
			result.success("修改成功!");
		}
		
		return result;
	}
	
	/**
	  *   通过id删除
	 * @param id
	 * @return
	 */
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		try {
			reportConfigService.delMain(id);
		} catch (Exception e) {
			log.error("删除失败",e.getMessage());
			return Result.error("删除失败!");
		}
		return Result.ok("删除成功!");
	}
	
	/**
	  *  批量删除
	 * @param ids
	 * @return
	 */
	@DeleteMapping(value = "/deleteBatch")
	public Result<ReportConfig> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<ReportConfig> result = new Result<ReportConfig>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			this.reportConfigService.removeByIds(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<ReportConfig> queryById(@RequestParam(name="id",required=true) String id) {
		Result<ReportConfig> result = new Result<ReportConfig>();
		ReportConfig reportConfig = reportConfigService.getById(id);
		if(reportConfig==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(reportConfig);
			result.setSuccess(true);
		}
		return result;
	}
	
	//===========================以下是子表信息操作相关API====================================
	
	/**
	  * 通过主表id查询战图显示配置明细表
	 * @param mainId
	 * @return
	 */
	@GetMapping(value = "/listReportConfigInfoByMainId")
	public Result<List<ReportConfigInfo>> queryReportConfigInfoListByMainId(@RequestParam(name="mainId",required=false) String mainId) {
		Result<List<ReportConfigInfo>> result = new Result<List<ReportConfigInfo>>();
		List<ReportConfigInfo> reportConfigInfoList = null;
		if (mainId != null) {
			reportConfigInfoList = reportConfigInfoService.selectByMainId(mainId);
            result.setResult(reportConfigInfoList);
            result.setSuccess(true);
            return result;
		}else return null;	
	}
	
	/**
     * 添加战图显示配置明细表
     *
     * @param reportConfigInfo
     * @return
     */
    @PostMapping(value = "/addReportConfigInfo")
    public Result<ReportConfigInfo> addReportConfigInfo(@RequestBody ReportConfigInfo reportConfigInfo) {
        Result<ReportConfigInfo> result = new Result<>();
        try {
            List<ReportConfigInfo> existInfoList =  reportConfigInfoService.findByMainAndSortId(reportConfigInfo.getConfigId(),reportConfigInfo.getEquipSortId());
            if (existInfoList.size() > 0){
                return Result.error("不可重复添加");
            }
            boolean ok = reportConfigInfoService.save(reportConfigInfo);
            if (ok) {
                result.setSuccess(true);
                result.setMessage("添加战图显示配置明细表成功.");
            } else {
                result.setSuccess(false);
                result.setMessage("添加战图显示配置明细表失败!");
            }
            return result;
        } catch (Exception e) {
            e.fillInStackTrace();
            result.setSuccess(false);
            result.setMessage("添加战图显示配置明细表过程中出现了异常: " + e.getMessage());
            return result;
        }
    }
    
    /**
     * 编辑战图显示配置明细表
     *
     * @param reportConfigInfo
     * @return
     */
    @PutMapping("/editReportConfigInfo")
    public Result<ReportConfigInfo> editReportConfigInfo(@RequestBody ReportConfigInfo reportConfigInfo) {
        Result<ReportConfigInfo> result = new Result<>();
        try {
            boolean ok = reportConfigInfoService.updateById(reportConfigInfo);
            if (ok) {
                result.setSuccess(true);
                result.setMessage("更新战图显示配置明细表成功.");
            } else {
                result.setSuccess(false);
                result.setMessage("更新战图显示配置明细表失败!");
            }
            return result;
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("更新数据过程中出现异常啦: " + e.getMessage());
            return result;
        }
    }
    
    /**
     * 通过id删除战图显示配置明细表
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/deleteReportConfigInfo")
    public Result<ReportConfigInfo> deleteReportConfigInfo(@RequestParam(name = "id", required = true) String id) {
        Result<ReportConfigInfo> result = new Result<>();
        try {
            boolean ok = reportConfigInfoService.removeById(id);
            if (ok) {
                result.setSuccess(true);
                result.setMessage("删除战图显示配置明细表成功.");
            } else {
                result.setSuccess(false);
                result.setMessage("删除战图显示配置明细表失败!");
            }
            return result;
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("删除战图显示配置明细表过程中出现异常啦: " + e.getMessage());
            return result;
        }
    }
	
	/**
     * 批量删除战图显示配置明细表
     *
     * @param ids
     * @return
     */
    @DeleteMapping(value = "/deleteBatchReportConfigInfo")
    public Result<ReportConfigInfo> deleteBatchReportConfigInfo(@RequestParam(name = "ids", required = true) String ids) {
        Result<ReportConfigInfo> result = new Result<ReportConfigInfo>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.reportConfigInfoService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

     /**
      * 通过主表id查询战图显示配置视频监控表
      * @param mainId
      * @return
      */
     @GetMapping(value = "/listReportConfigVideoByMainId")
     public Result<List<ReportConfigVideo>> queryReportConfigVideoListByMainId(@RequestParam(name="mainId",required=false) String mainId) {
         Result<List<ReportConfigVideo>> result = new Result<List<ReportConfigVideo>>();
         List<ReportConfigVideo> reportConfigVideoList = null;
         if (mainId != null) {
             reportConfigVideoList = reportConfigVideoService.selectByMainId(mainId);
             return Result.ok(reportConfigVideoList);
         }else {
             return Result.error("数据为空");
         }
     }

     /**
      * 添加战图显示配置视频监控表
      *
      * @param reportConfigVideo
      * @return
      */
     @PostMapping(value = "/addReportConfigVideo")
     public Result<ReportConfigVideo> addReportConfigVideo(@RequestBody ReportConfigVideo reportConfigVideo) {
         Result<ReportConfigVideo> result = new Result<>();
         try {
             List<String> newItemList = Arrays.asList(reportConfigVideo.getEquipIdList().split(","));
             List<ReportConfigVideo> reportConfigVideoList = reportConfigVideoService.selectByMainId(reportConfigVideo.getConfigId());
             List<String> addItemList = new ArrayList<>();  //新增的
             List<ReportConfigVideo> delItemList = new ArrayList<>();  //旧的需要删除的部分
             if (reportConfigVideoList.size() > 0 ){
                 Map<String,ReportConfigVideo> oldItemMap = reportConfigVideoList.stream().collect(Collectors.toMap(ReportConfigVideo::getEquipId, Function.identity()));
                 for (Map.Entry<String,ReportConfigVideo> entry :oldItemMap.entrySet()){
                     if(!newItemList.contains(entry.getKey())){
                         delItemList.add(entry.getValue());
                         entry.getValue().setDelFlag("1");
                     }
                 }
                 for (String add:newItemList){   //在原先旧的里没有的 -> 是需要新增进去的
                     if (oldItemMap.get(add) == null){
                         addItemList.add(add);
                     }
                 }
             } else {
                 addItemList.addAll(newItemList);
             }
             if (addItemList.size() > 0){
                 List<ReportConfigVideo> addVideoList = new ArrayList<>();
                 for (String add:addItemList){
                     ReportConfigVideo addVideo = new ReportConfigVideo();
                     addVideo.setConfigId(reportConfigVideo.getConfigId());

                     addVideo.setEquipId(add);
                     addVideo.setNo(0);
                     addVideoList.add(addVideo);
                 }
                 reportConfigVideoService.saveBatch(addVideoList);
             }
             if (delItemList.size() > 0 ){
                 reportConfigVideoService.delBatch(SsoUtil.getLoginUser().getId(),new Date(),delItemList);
             }
             result.setSuccess(true);
             result.setMessage("添加战图显示配置视频监控表成功.");
             return result;
         } catch (Exception e) {
             log.error(e.getMessage(),e.fillInStackTrace());
             result.setSuccess(false);
             result.setMessage("添加战图显示配置视频监控表过程中出现了异常: " + e.getMessage());
             return result;
         }
     }

     /**
      * 编辑战图显示配置视频监控表
      *
      * @param reportConfigVideo
      * @return
      */
     @PutMapping("/editReportConfigVideo")
     public Result<ReportConfigVideo> editReportConfigVideo(@RequestBody ReportConfigVideo reportConfigVideo) {
         Result<ReportConfigVideo> result = new Result<>();
         try {
             boolean ok = reportConfigVideoService.updateById(reportConfigVideo);
             if (ok) {
                 result.setSuccess(true);
                 result.setMessage("更新战图显示配置视频监控表成功.");
             } else {
                 result.setSuccess(false);
                 result.setMessage("更新战图显示配置视频监控表失败!");
             }
             return result;
         } catch (Exception e) {
             result.setSuccess(false);
             result.setMessage("更新数据过程中出现异常啦: " + e.getMessage());
             return result;
         }
     }

     /**
      * 通过id删除战图显示配置视频监控表
      *
      * @param id
      * @return
      */
     @DeleteMapping(value = "/deleteReportConfigVideo")
     public Result<ReportConfigVideo> deleteReportConfigVideo(@RequestParam(name = "id", required = true) String id) {
         Result<ReportConfigVideo> result = new Result<>();
         try {
             boolean ok = reportConfigVideoService.removeById(id);
             if (ok) {
                 result.setSuccess(true);
                 result.setMessage("删除战图显示配置视频监控表成功.");
             } else {
                 result.setSuccess(false);
                 result.setMessage("删除战图显示配置视频监控表失败!");
             }
             return result;
         } catch (Exception e) {
             result.setSuccess(false);
             result.setMessage("删除战图显示配置视频监控表过程中出现异常啦: " + e.getMessage());
             return result;
         }
     }

     /**
      * 批量删除战图显示配置视频监控表
      *
      * @param ids
      * @return
      */
     @DeleteMapping(value = "/deleteBatchReportConfigVideo")
     public Result<ReportConfigVideo> deleteBatchReportConfigVideo(@RequestParam(name = "ids", required = true) String ids) {
         Result<ReportConfigVideo> result = new Result<ReportConfigVideo>();
         if (ids == null || "".equals(ids.trim())) {
             result.error500("参数不识别！");
         } else {
             this.reportConfigVideoService.removeByIds(Arrays.asList(ids.split(",")));
             result.success("删除成功!");
         }
         return result;
     }


     /**
      * 导出excel
      *
      * @param request
      * @param response
      */
     @RequestMapping(value = "/exportXls")
     public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
         // Step.1 组装查询条件
         QueryWrapper<ReportConfig> queryWrapper = null;
         try {
             String paramsStr = request.getParameter("paramsStr");
             if (oConvertUtils.isNotEmpty(paramsStr)) {
                 String deString = URLDecoder.decode(paramsStr, "UTF-8");
                 ReportConfig reportConfig = JSON.parseObject(deString, ReportConfig.class);
                 queryWrapper = QueryGenerator.initQueryWrapper(reportConfig, request.getParameterMap());
             }
         } catch (UnsupportedEncodingException e) {
             e.printStackTrace();
         }
         //Step.2 AutoPoi 导出Excel
         ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
         List<ReportConfigPage> pageList = new ArrayList<ReportConfigPage>();
         List<ReportConfig> reportConfigList = reportConfigService.list(queryWrapper);
         for (ReportConfig reportConfig : reportConfigList) {
             ReportConfigPage vo = new ReportConfigPage();
             BeanUtils.copyProperties(reportConfig, vo);
             List<ReportConfigInfo> reportConfigInfoList = reportConfigInfoService.selectByMainId(reportConfig.getId());
             vo.setReportConfigInfoList(reportConfigInfoList);
             List<ReportConfigVideo> reportConfigVideoList = reportConfigVideoService.selectByMainId(reportConfig.getId());
             vo.setReportConfigVideoList(reportConfigVideoList);
             pageList.add(vo);
         }
         //导出文件名称
         mv.addObject(NormalExcelConstants.FILE_NAME, "战图显示配置列表");
         mv.addObject(NormalExcelConstants.CLASS, ReportConfigPage.class);
         mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("战图显示配置列表数据", "导出人:Jeecg", "导出信息"));
         mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
         return mv;
     }

     /**
      * 通过excel导入数据
      *
      * @param request
      * @param response
      * @return
      */
     @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
     public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
         MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
         Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
         for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
             MultipartFile file = entity.getValue();// 获取上传文件对象
             ImportParams params = new ImportParams();
             params.setTitleRows(2);
             params.setHeadRows(1);
             params.setNeedSave(true);
             try {
                 List<ReportConfigPage> list = ExcelImportUtil.importExcel(file.getInputStream(), ReportConfigPage.class, params);
                 for (ReportConfigPage page : list) {
                     ReportConfig po = new ReportConfig();
                     BeanUtils.copyProperties(page, po);
                     reportConfigService.saveMain(po, page.getReportConfigInfoList(),page.getReportConfigVideoList());
                 }
                 return Result.ok("文件导入成功！数据行数:" + list.size());
             } catch (Exception e) {
                 log.error(e.getMessage(),e);
                 return Result.error("文件导入失败:"+e.getMessage());
             } finally {
                 try {
                     file.getInputStream().close();
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
             }
         }
         return Result.ok("文件导入失败！");
     }

     public static void main(String[] args) {
         HashMap<String, Object> paramsMap = new HashMap<String, Object>();
         JSONObject json = HttpSend.execute(paramsMap,"accessToken");
         JSONObject jsonResult = json.getJSONObject("result");
         JSONObject jsonData = jsonResult.getJSONObject("data");
         String token = jsonData.getString("accessToken");
         System.out.println(token);
         String msg = jsonResult.getString("msg");
         System.out.println("msg:" + msg);
         //获取设备列表
//        paramsMap = new HashMap<String, Object>();
//        paramsMap.put("token",token);
//        paramsMap.put("queryRange","1-5");
//        json = HttpSend.execute(paramsMap,"deviceList");
//        System.out.println("设备列表返回:" + json);
     }
}
